package com.calvin.study.threadsafe.lock.viewlock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.calvin.study.utils.Print;
import com.calvin.study.utils.ThreadUtil;

//显示锁线程间通信Demo
public class ConditionDemo01 {

	static Lock lock = new ReentrantLock();
	static private Condition cond = lock.newCondition();

	static class WaitTarget implements Runnable {
		@Override
		public void run() {
			lock.lock();
			try {
				Print.tcfo("我是等待方");
				cond.await();
				Print.tco("收到通知，等待方继续执行");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}

		}
	}

	// 通知线程的异步目标任务
	static class NotifyTarget implements Runnable {
		public void run() {
			lock.lock(); // ③抢锁
			try {
				Print.tcfo("我是通知方");
				cond.signal(); // ④发送通知
				Print.tco("发出通知了， 但是线程还没有立马释放锁");
			} finally {
				lock.unlock(); // ⑤释放锁之后， 等待线程才能获得锁
			}
		}
	}

	public static void main(String[] args) throws InterruptedException {
		// 创建等待线程
		Thread waitThread = new Thread(new WaitTarget(), "WaitThread");
		// 启动等待线程
		waitThread.start();
		ThreadUtil.sleepSeconds(1); // 稍等一下
		// 创建通知线程
		Thread notifyThread = new Thread(new NotifyTarget(), "NotifyThread");
		// 启动通知线程
		notifyThread.start();
	}

}
